import tkinter as tk
from tkinter import ttk, messagebox
import sys
import os
import customtkinter

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from core.utils.logger import logger, info, error, debug, warning
from core.utils.error_handler import ErrorHandler
from core.utils.i18n import i18n, set_language, get_current_language

info("=== STARTING ALI BAO BAO ===")

try:
    from core.services.auth_service import AuthService
    from core.services.product_service import ProductService
    from ui.styles.theme import Theme
    
    # 导入页面类
    from ui.pages.welcome_page import WelcomePage
    from ui.pages.login_page import LoginPage
    from ui.pages.register_page import RegisterPage
    from ui.pages.product_page import ProductPage
    from ui.pages.product_detail_page import ProductDetailPage
    from ui.pages.product_reviews_page import ProductReviewsPage
    from ui.pages.account_page import AccountPage
    from ui.pages.cart_page import CartPage
    from ui.pages.orders_page import OrdersPage
    from ui.pages.order_success_page import OrderSuccessPage
    
    # 导入管理员页面
    from ui.pages.admin_login_page import AdminLoginPage
    from ui.pages.admin_register_page import AdminRegisterPage
    from ui.pages.admin_page import AdminPage
    
    info("All imports successful")
    
except ImportError as e:
    error(f"❌ Import error: {e}")
    import traceback
    traceback.print_exc()
    input("Press Enter to exit...")
    sys.exit(1)

class MainApplication(customtkinter.CTk):
    def __init__(self):
        super().__init__()
        
        self.title("Ali Bao Bao - E-commerce Platform")
        self.geometry("1200x800")
        self.minsize(1000, 700)
        
        # 初始化国际化系统
        self._init_i18n()
        
        # 配置样式
        Theme.configure_styles()
        
        # 初始化服务
        self.auth_service = AuthService()
        self.product_service = ProductService()
        
        # 初始化订单服务
        from core.services.order_service import OrderService
        self.order_service = OrderService()
        
        # 初始化评价服务
        from core.services.review_service import ReviewService
        self.review_service = ReviewService()
        
        # 初始化推荐服务
        from core.services.recommendation_service import RecommendationService
        self.recommendation_service = RecommendationService()
        
        # 初始化管理员服务
        from core.services.admin_service import AdminService
        self.admin_service = AdminService()
        
        # 初始化购物车（默认为游客）
        from core.models.cart import ShoppingCart
        self.shopping_cart = ShoppingCart(controller=self, user_id="guest")
        
        # 创建容器 (使用 CustomTkinter Frame)
        self.container = customtkinter.CTkFrame(self, fg_color="transparent")
        self.container.pack(fill="both", expand=True)
        self.container.grid_rowconfigure(0, weight=1)
        self.container.grid_columnconfigure(0, weight=1)
        
        # 页面字典
        self.pages = {}
        
        # 商品详情页面缓存（最多缓存3个）
        self.detail_page_cache = {}
        self.max_detail_cache = 3

        # 初始化所有页面
        page_classes = [WelcomePage, LoginPage, RegisterPage, ProductPage, AccountPage, CartPage, OrdersPage, OrderSuccessPage, ProductReviewsPage, AdminLoginPage, AdminRegisterPage, AdminPage]

        info("=== CREATING PAGES ===")
        for PageClass in page_classes:
            page_name = PageClass.__name__
            try:
                debug(f"Creating {page_name}...")
                page = PageClass(parent=self.container, controller=self)
                self.pages[page_name] = page
                page.grid(row=0, column=0, sticky="nsew")
                info(f"{page_name} created successfully")
            except Exception as e:
                error(f"❌ Error creating page {page_name}: {e}")
                ErrorHandler.log_exception(e, f"Create page {page_name}")
        
        debug(f"📄 Final pages dictionary: {list(self.pages.keys())}")
        
        # 显示欢迎页面
        self.show_page("WelcomePage")
    
    def _init_i18n(self):
        """初始化国际化系统"""
        try:
            # 从设置文件加载语言偏好
            from core.services.data_manager import DataManager
            dm = DataManager()
            settings = dm.load_data('settings.json') or {}
            language = settings.get('language', 'en_US')
            
            # 设置语言
            if set_language(language):
                info(f"Language initialized: {language}")
            else:
                warning(f"Failed to load language {language}, using default")
                
        except Exception as e:
            error(f"Failed to initialize i18n: {e}")
    
    def refresh_all_pages(self):
        """刷新所有页面的语言显示"""
        try:
            info("🔄 Refreshing all pages for language change...")
            
            # 刷新所有页面
            for page_name, page in self.pages.items():
                try:
                    if hasattr(page, 'refresh_language'):
                        page.refresh_language()
                        debug(f"✅ Refreshed {page_name}")
                    else:
                        # 如果没有 refresh_language 方法，重新创建控件
                        if hasattr(page, 'create_widgets'):
                            # 清除现有控件
                            for widget in page.winfo_children():
                                widget.destroy()
                            # 重新创建控件
                            page.create_widgets()
                            # 更新数据
                            if hasattr(page, 'update_data'):
                                page.update_data()
                            debug(f"✅ Recreated widgets for {page_name}")
                except Exception as e:
                    error(f"Failed to refresh {page_name}: {e}")
            
            info("✅ All pages refreshed successfully")
            
        except Exception as e:
            error(f"Failed to refresh pages: {e}")
    
    def change_language(self, lang_code):
        """切换语言并刷新所有页面"""
        try:
            if set_language(lang_code):
                self.refresh_all_pages()
                info(f"Language changed to: {lang_code}")
                return True
            else:
                error(f"Failed to change language to: {lang_code}")
                return False
        except Exception as e:
            error(f"Error changing language: {e}")
            return False
    
    def show_page(self, page_name, **kwargs):
        debug(f"Showing page: {page_name}")
        debug(f"Available pages: {list(self.pages.keys())}")
        
        # 特殊处理需要动态创建的页面
        if page_name == 'ProductDetailPage' and 'product_id' in kwargs:
            self._show_product_detail_page(kwargs['product_id'])
            return
        
        if page_name in self.pages:
            page = self.pages[page_name]
            page.tkraise()
            
            # 更新页面数据
            # Manage mouse-wheel: disable on AccountPage (per UX request), enable on others
            try:
                # Unbind globally first to avoid multiple handlers
                from ui.components.scrollable_frame import ScrollableFrame
                # Unbind all by default
                ScrollableFrame.unbind_all_mouse_wheel()
            except Exception as e:
                debug(f"Error unbinding mouse wheel: {e}")

            try:
                if page_name == 'AccountPage':
                    # keep mouse wheel disabled for account page
                    pass
                else:
                    # If the page has a scrollable_frame, enable bindings
                    if hasattr(page, 'scrollable_frame') and hasattr(page, 'bind_mouse_wheel'):
                        page.bind_mouse_wheel()
                    elif hasattr(page, 'scrollable_frame'):
                        # fallback: try to access the ScrollableFrame instance and bind
                        try:
                            page.get_scrollable_frame().bind_mouse_wheel()
                        except Exception as e:
                            debug(f"Error binding mouse wheel: {e}")
            except Exception as e:
                debug(f"Error in mouse wheel handling: {e}")

            # Update page data after bindings
            if hasattr(page, 'update_data'):
                page.update_data()
            
            # 如果页面有on_show方法，调用它
            if hasattr(page, 'on_show'):
                page.on_show()
                
            info(f"Successfully showed page: {page_name}")
        else:
            error(f"Page {page_name} does not exist!")
            error(f"Available pages are: {list(self.pages.keys())}")
    
    def _show_product_detail_page(self, product_id):
        """显示商品详情页面（带缓存机制）"""
        try:
            # 检查缓存中是否已有该商品的详情页面
            if product_id in self.detail_page_cache:
                detail_page = self.detail_page_cache[product_id]
                # 将页面移到最前面
                detail_page.tkraise()
                info(f"Using cached ProductDetailPage for product: {product_id}")
                return
            
            # 如果缓存已满，清理最旧的页面
            if len(self.detail_page_cache) >= self.max_detail_cache:
                self._cleanup_oldest_detail_page()
            
            # 创建新的商品详情页面
            from ui.pages.product_detail_page import ProductDetailPage
            detail_page = ProductDetailPage(parent=self.container, controller=self, product_id=product_id)
            
            # 将详情页面添加到主容器中
            detail_page.grid(row=0, column=0, sticky="nsew")
            detail_page.tkraise()
            
            # 绑定鼠标滚轮
            if hasattr(detail_page, 'scrollable_frame') and hasattr(detail_page, 'bind_mouse_wheel'):
                detail_page.bind_mouse_wheel()
            
            # 添加到缓存
            self.detail_page_cache[product_id] = detail_page
            
            info(f"Successfully created and cached ProductDetailPage for product: {product_id}")
            
        except Exception as e:
            error(f"Error showing ProductDetailPage: {e}")
            messagebox.showerror("Error", f"Cannot display product details: {e}")
    
    def _cleanup_oldest_detail_page(self):
        """清理最旧的商品详情页面"""
        if not self.detail_page_cache:
            return
        
        # 获取第一个（最旧的）页面
        oldest_product_id = next(iter(self.detail_page_cache))
        oldest_page = self.detail_page_cache[oldest_product_id]
        
        try:
            # 从容器中移除
            oldest_page.grid_forget()
            # 销毁页面
            oldest_page.destroy()
            # 从缓存中移除
            del self.detail_page_cache[oldest_product_id]
            info(f"Cleaned up detail page for product: {oldest_product_id}")
        except Exception as e:
            error(f"Error cleaning up detail page: {e}")
    
    def _cleanup_all_detail_pages(self):
        """清理所有商品详情页面"""
        for product_id in list(self.detail_page_cache.keys()):
            try:
                page = self.detail_page_cache[product_id]
                # 检查应用是否已销毁
                if hasattr(self, 'winfo_exists') and not self.winfo_exists():
                    # 应用已销毁，直接清理缓存
                    del self.detail_page_cache[product_id]
                    continue
                
                # 检查页面是否仍然存在
                if hasattr(page, 'winfo_exists') and page.winfo_exists():
                    page.grid_forget()
                    page.destroy()
                del self.detail_page_cache[product_id]
            except Exception as e:
                error(f"Error cleaning up detail page {product_id}: {e}")
        info("All detail pages cleaned up")
    
    def update_cart_user(self):
        """更新购物车的用户ID（在用户登录/登出时调用）"""
        if self.auth_service.is_logged_in():
            user_id = self.auth_service.current_user.user_id
        else:
            user_id = "guest"
        
        self.shopping_cart.update_user_id(user_id)
        info(f"🛒 Cart updated for user: {user_id}")
    
    def refresh_current_page_reviews(self):
        """刷新当前页面的评价列表（如果当前页面是商品详情页）"""
        try:
            # 检查当前显示的页面是否是商品详情页
            current_page = None
            for page_name, page in self.pages.items():
                if hasattr(page, 'winfo_viewable') and page.winfo_viewable():
                    current_page = page
                    break
            
            # 检查是否是缓存的商品详情页
            if not current_page:
                for product_id, detail_page in self.detail_page_cache.items():
                    if hasattr(detail_page, 'winfo_viewable') and detail_page.winfo_viewable():
                        current_page = detail_page
                        break
            
            # 如果当前页面是商品详情页，刷新评价
            if current_page and hasattr(current_page, 'refresh_reviews'):
                info("🔄 Refreshing review list for current product detail page")
                current_page.refresh_reviews()
            else:
                debug("Current page is not product detail page, no need to refresh reviews")
                
        except Exception as e:
            error(f"Failed to refresh current page reviews: {e}")

def main():
    app = None
    try:
        info("Starting Ali Bao Bao...")
        app = MainApplication()
        app.mainloop()
    except Exception as e:
        error(f"💥 Program startup error: {e}")
        import traceback
        traceback.print_exc()
        input("Press Enter to exit...")
    finally:
        # 程序退出时清理所有详情页面
        if app and hasattr(app, '_cleanup_all_detail_pages'):
            try:
                app._cleanup_all_detail_pages()
            except Exception as e:
                error(f"Error during cleanup: {e}")

if __name__ == "__main__":
    main()